<!DOCTYPE html>
<html lang="en">





<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="My Personal Website For Blog">
  <meta name="author" content="黄宇辉">
  <meta name="keywords" content="learning note,hexo blog">
  <title>Shiro之自定义realm及其加密 - 欢迎参观小灰灰的网站哟 ヾ(◍°∇°◍)ﾉﾞ ~</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/vs2015.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->
<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">

<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">

<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/js/utils.js" ></script>
</head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>ANONYMOUS</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                Home
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                Archives
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                Tags
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                About
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2019-08-01 18:49">
      August 1, 2019 pm
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      1.8k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      26
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
            <article class="markdown-body">
              <h2 id="学习笔记-Shiro之自定义realm及其加密"><a href="#学习笔记-Shiro之自定义realm及其加密" class="headerlink" title="学习笔记 :  Shiro之自定义realm及其加密"></a>学习笔记 :  Shiro之自定义realm及其加密</h2><h3 id="自定义Realm"><a href="#自定义Realm" class="headerlink" title="自定义Realm"></a>自定义Realm</h3><p><em><code>Realm</code> : 域,Shiro从Realm获取安全数据(如用户、角色、权限),就是说SecurityManager要验证用户身份,那么它需要从Realm获取相应的用户进行比较以确定用户身份是否合法. 也需要从Realm得到用户相应的角色 / 权限进行验证用户是否能进行操作,可以把Realm看成 DataSource,即安全数据源. 如我们之前的ini配置方式使用的是<code>org.apache.shiro.realm.text.IniRealm</code>接口</em></p>
<p><em>org.apache.shiro.realm.Realm接口如下所示 :</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-comment">//返回一个唯一的Realm名字</span>
<span class="hljs-function">String <span class="hljs-title">getName</span><span class="hljs-params">()</span></span>; 
<span class="hljs-comment">//判断此Realm是否支持此Token</span>
<span class="hljs-function"><span class="hljs-keyword">boolean</span> <span class="hljs-title">supports</span><span class="hljs-params">(AuthenticationToken token)</span></span>; 
<span class="hljs-comment">//根据Token获取认证信息</span>
<span class="hljs-function">AuthenticationInfo <span class="hljs-title">getAuthenticationInfo</span><span class="hljs-params">(AuthenticationToken token)</span> <span class="hljs-keyword">throws</span> AuthenticationException</span>;</code></pre></div>

<p><em>下面通过自定义Realm来实现一个简单的用户身份验证程序~</em></p>
<ol>
<li><p><em>pom.xml : Maven依赖</em></p>
<div class="hljs"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependencies</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>junit<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>junit<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>4.11<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">scope</span>&gt;</span>test<span class="hljs-tag">&lt;/<span class="hljs-name">scope</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- Shiro核心包 --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.apache.shiro<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>shiro-core<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.3.2<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- slf4j的接口实现 --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.slf4j<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>slf4j-log4j12<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.7.12<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>commons-logging<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>commons-logging<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.2<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependencies</span>&gt;</span></code></pre></div>
</li>
<li><p><em>my-shiro.ini : 存储用户身份信息(账户=密码)</em></p>
<div class="hljs"><pre><code class="hljs ini"><span class="hljs-comment">#自定义realm</span>
<span class="hljs-attr">myRealm</span> = pers.huangyuhui.realm.MyRealm
<span class="hljs-comment">#指定SecurityManager的realms实现</span>
<span class="hljs-attr">securityManager.realm</span> = <span class="hljs-variable">$myRealm</span></code></pre></div>
</li>
<li><p><em>MyRealm.java : 自定义Realm,模拟从数据库中获取用户信息</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.realm;

<span class="hljs-keyword">import</span> org.apache.shiro.authc.AuthenticationException;
<span class="hljs-keyword">import</span> org.apache.shiro.authc.AuthenticationInfo;
<span class="hljs-keyword">import</span> org.apache.shiro.authc.AuthenticationToken;
<span class="hljs-keyword">import</span> org.apache.shiro.authc.SimpleAuthenticationInfo;
<span class="hljs-keyword">import</span> org.apache.shiro.authz.AuthorizationInfo;
<span class="hljs-keyword">import</span> org.apache.shiro.realm.AuthorizingRealm;
<span class="hljs-keyword">import</span> org.apache.shiro.subject.PrincipalCollection;

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@project</span>: shiro-learning
 * <span class="hljs-doctag">@description</span>: 自定义Realm
 * <span class="hljs-doctag">@author</span>: 黄宇辉
 * <span class="hljs-doctag">@date</span>: 8/1/2019-5:59 PM
 * <span class="hljs-doctag">@version</span>: 1.0
 * <span class="hljs-doctag">@website</span>: https://yubuntu0109.github.io/
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyRealm</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">AuthorizingRealm</span> </span>&#123;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> <span class="hljs-string">"myRealm"</span>; <span class="hljs-comment">//区分不同的Realm</span>
    &#125;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-comment">//授权操作</span>
    <span class="hljs-function"><span class="hljs-keyword">protected</span> AuthorizationInfo <span class="hljs-title">doGetAuthorizationInfo</span><span class="hljs-params">(PrincipalCollection principals)</span> </span>&#123;
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;
    &#125;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-comment">//认证操作:其token存储着传入的用户登录信息(usernamePasswordToken)</span>
    <span class="hljs-function"><span class="hljs-keyword">protected</span> AuthenticationInfo <span class="hljs-title">doGetAuthenticationInfo</span><span class="hljs-params">(AuthenticationToken token)</span> <span class="hljs-keyword">throws</span> AuthenticationException </span>&#123;

        <span class="hljs-comment">//获取并验证用户账号信息</span>
        String username = (String) token.getPrincipal();
        <span class="hljs-keyword">if</span> (!<span class="hljs-string">"root"</span>.equals(username)) &#123;
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;
        &#125;
        <span class="hljs-comment">//假设用户密码信息</span>
        String password = <span class="hljs-string">"yubuntu0109"</span>;

        <span class="hljs-comment">//SimpleAuthenticationInfo(Object principal, Object credentials, String realmName)</span>
        SimpleAuthenticationInfo info = <span class="hljs-keyword">new</span> SimpleAuthenticationInfo(username, password, getName());
        <span class="hljs-keyword">return</span> info;
    &#125;
&#125;</code></pre></div>
</li>
<li><p><em>LoginByMyRealm.java : 验证用户登录信息</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.realm;

<span class="hljs-keyword">import</span> org.apache.shiro.SecurityUtils;
<span class="hljs-keyword">import</span> org.apache.shiro.authc.AuthenticationException;
<span class="hljs-keyword">import</span> org.apache.shiro.authc.IncorrectCredentialsException;
<span class="hljs-keyword">import</span> org.apache.shiro.authc.UnknownAccountException;
<span class="hljs-keyword">import</span> org.apache.shiro.authc.UsernamePasswordToken;
<span class="hljs-keyword">import</span> org.apache.shiro.config.IniSecurityManagerFactory;
<span class="hljs-keyword">import</span> org.apache.shiro.mgt.SecurityManager;
<span class="hljs-keyword">import</span> org.apache.shiro.subject.Subject;
<span class="hljs-keyword">import</span> org.apache.shiro.util.Factory;

<span class="hljs-comment">/**
 * Shiro认证测试:验证用户登录信息
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">loginByMyRealm</span> </span>&#123;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;
        <span class="hljs-comment">//1:加载配置文件,创建SecurityManager工厂对象</span>
        Factory&lt;SecurityManager&gt; factory = <span class="hljs-keyword">new</span> IniSecurityManagerFactory(<span class="hljs-string">"classpath:my-shiro.ini"</span>);
        <span class="hljs-comment">//2:获得securityManager实例对象</span>
        SecurityManager securityManager = factory.getInstance();
        <span class="hljs-comment">//3:将securityManger实例绑定到当前运行环境中,便于访问</span>
        SecurityUtils.setSecurityManager(securityManager);
        <span class="hljs-comment">//4:创建当前登录的主体</span>
        Subject currentUser = SecurityUtils.getSubject();
        <span class="hljs-comment">//5:绑定主体登录的身份/凭证,既账户及密码</span>
        UsernamePasswordToken token = <span class="hljs-keyword">new</span> UsernamePasswordToken(<span class="hljs-string">"root"</span>, <span class="hljs-string">"yubuntu0109"</span>);
        <span class="hljs-comment">//6:主体登录</span>
        <span class="hljs-keyword">try</span> &#123;
            currentUser.login(token);
            System.out.println(<span class="hljs-string">"用户身份是否验证成功 :"</span> + currentUser.isAuthenticated());
        &#125; <span class="hljs-keyword">catch</span> (UnknownAccountException e) &#123;
            System.err.println(<span class="hljs-string">"用户账户错误 !"</span>);
        &#125; <span class="hljs-keyword">catch</span> (IncorrectCredentialsException e) &#123;
            System.err.println(<span class="hljs-string">"用户密码错误 !"</span>);
        &#125; <span class="hljs-keyword">catch</span> (AuthenticationException e) &#123;
            e.printStackTrace();
        &#125;
        <span class="hljs-comment">//8:注销登录</span>
        currentUser.logout();
        System.out.println(<span class="hljs-string">"身份身份是否注销成功 :"</span> + !currentUser.isAuthenticated());

    &#125;
&#125;</code></pre></div>
</li>
<li><p><em>程序运行结果如下所示 :</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-comment">// ······</span>
用户身份是否验证成功 :<span class="hljs-keyword">true</span>
<span class="hljs-comment">// ······</span>
身份身份是否注销成功 :<span class="hljs-keyword">true</span></code></pre></div>



</li>
</ol>
<h3 id="加密Realm"><a href="#加密Realm" class="headerlink" title="加密Realm"></a>加密Realm</h3><p><em>Shiro提供了base64和16进制字符串编码 / 解码的API支持,方便一些编码解码操作. Shiro内部的一些数据的存储及表示都使用了 base64和16进制字符串</em></p>
<h4 id="散列算法"><a href="#散列算法" class="headerlink" title="散列算法"></a>散列算法</h4><p><em>散列算法一般用于生成数据的摘要信息,是一种不可逆的算法,一般适合存储密码之类的数据,常见的散列算法如<code>MD5</code>、<code>SHA</code>等. 一般进行散列时最好提供一个salt(盐),比密码”admin”加密后产生的散列值是”21232f297a57a5a743894a0e4a801fc3”,其可以到一些MD5解密网站很容易的通过散列值得到密码”admin”,即如果直接对密码进行散列相对来说破解更容易,此时我们可以加一些只有系统知道的干扰数据,如在密码中混入用户ID及用户名(加盐操作),既而这样生成的散列值相对来说更难破解哟!</em></p>
<h4 id="加密自定义Realm"><a href="#加密自定义Realm" class="headerlink" title="加密自定义Realm"></a>加密自定义Realm</h4><p><em>接下来通过使用MD5加密自定义Realm,来完成一个简单的用户身份验证程序~</em></p>
<ol>
<li><p><em>pom.xml : Maven依赖(同上)</em></p>
</li>
<li><p><em>en-shiro.ini : 存储用户身份及加密配置信息</em></p>
<div class="hljs"><pre><code class="hljs ini"><span class="hljs-section">[main]</span>
<span class="hljs-comment">#定义凭证匹配器</span>
<span class="hljs-attr">credentialsMatcher</span> = org.apache.shiro.authc.credential.HashedCredentialsMatcher
<span class="hljs-comment">#散列算法</span>
<span class="hljs-attr">credentialsMatcher.hashAlgorithmName</span> = md5
<span class="hljs-comment">#散列次数</span>
<span class="hljs-attr">credentialsMatcher.hashIterations</span> = <span class="hljs-number">10</span>
<span class="hljs-comment">#将凭证匹配器设置到realm</span>
<span class="hljs-attr">myRealm</span> = pers.huangyuhui.encryption.EncryRealm
<span class="hljs-attr">myRealm.credentialsMatcher</span> = <span class="hljs-variable">$credentialsMatcher</span>
<span class="hljs-attr">securityManager.realms</span> = <span class="hljs-variable">$myRealm</span></code></pre></div>
</li>
<li><p><em>EncryRealm.java : 自定义Realm,模拟从数据库中获取用户信息</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.encryption;

<span class="hljs-keyword">import</span> org.apache.shiro.authc.AuthenticationException;
<span class="hljs-keyword">import</span> org.apache.shiro.authc.AuthenticationInfo;
<span class="hljs-keyword">import</span> org.apache.shiro.authc.AuthenticationToken;
<span class="hljs-keyword">import</span> org.apache.shiro.authc.SimpleAuthenticationInfo;
<span class="hljs-keyword">import</span> org.apache.shiro.authz.AuthorizationInfo;
<span class="hljs-keyword">import</span> org.apache.shiro.realm.AuthorizingRealm;
<span class="hljs-keyword">import</span> org.apache.shiro.subject.PrincipalCollection;
<span class="hljs-keyword">import</span> org.apache.shiro.util.ByteSource;

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@project</span>: shiro-learning
 * <span class="hljs-doctag">@description</span>: 加密Realm
 * <span class="hljs-doctag">@author</span>: 黄宇辉
 * <span class="hljs-doctag">@date</span>: 8/1/2019-7:58 PM
 * <span class="hljs-doctag">@version</span>: 1.0
 * <span class="hljs-doctag">@website</span>: https://yubuntu0109.github.io/
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EncryRealm</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">AuthorizingRealm</span> </span>&#123;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> <span class="hljs-string">"pwdRealm"</span>; <span class="hljs-comment">//区分不同的Realm</span>
    &#125;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-comment">//授权操作</span>
    <span class="hljs-function"><span class="hljs-keyword">protected</span> AuthorizationInfo <span class="hljs-title">doGetAuthorizationInfo</span><span class="hljs-params">(PrincipalCollection principals)</span> </span>&#123;
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;
    &#125;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-comment">//认证操作</span>
    <span class="hljs-function"><span class="hljs-keyword">protected</span> AuthenticationInfo <span class="hljs-title">doGetAuthenticationInfo</span><span class="hljs-params">(AuthenticationToken token)</span> <span class="hljs-keyword">throws</span> AuthenticationException </span>&#123;

        <span class="hljs-comment">//获取用户账户信息</span>
        String username = token.getPrincipal().toString();
        <span class="hljs-keyword">if</span> (!<span class="hljs-string">"root"</span>.equals(username)) &#123;
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;
        &#125;
        <span class="hljs-comment">//MD5加密后的用户密码信息</span>
        String password = <span class="hljs-string">"f3005f7acf36cec973498845460b0c33"</span>;<span class="hljs-comment">//password + username + 10</span>
        <span class="hljs-comment">//指定盐值:ByteSource.Util.bytes(username)</span>
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> SimpleAuthenticationInfo(username, password, ByteSource.Util.bytes(username), getName());
    &#125;
&#125;</code></pre></div>
</li>
<li><p><em>LoginByMyRealm.java : 验证用户登录信息</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.encryption;

<span class="hljs-keyword">import</span> org.apache.shiro.SecurityUtils;
<span class="hljs-keyword">import</span> org.apache.shiro.authc.AuthenticationException;
<span class="hljs-keyword">import</span> org.apache.shiro.authc.IncorrectCredentialsException;
<span class="hljs-keyword">import</span> org.apache.shiro.authc.UnknownAccountException;
<span class="hljs-keyword">import</span> org.apache.shiro.authc.UsernamePasswordToken;
<span class="hljs-keyword">import</span> org.apache.shiro.config.IniSecurityManagerFactory;
<span class="hljs-keyword">import</span> org.apache.shiro.mgt.SecurityManager;
<span class="hljs-keyword">import</span> org.apache.shiro.subject.Subject;
<span class="hljs-keyword">import</span> org.apache.shiro.util.Factory;

<span class="hljs-comment">/**
 * Shiro认证测试:验证用户登录信息
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">loginByMyRealm</span> </span>&#123;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;
        <span class="hljs-comment">//1:加载配置文件,创建SecurityManager工厂对象</span>
        Factory&lt;SecurityManager&gt; factory = <span class="hljs-keyword">new</span> IniSecurityManagerFactory(<span class="hljs-string">"classpath:en-shiro.ini"</span>);
        <span class="hljs-comment">//2:获得securityManager实例对象</span>
        SecurityManager securityManager = factory.getInstance();
        <span class="hljs-comment">//3:将securityManger实例绑定到当前运行环境中,便于访问</span>
        SecurityUtils.setSecurityManager(securityManager);
        <span class="hljs-comment">//4:创建当前登录的主体</span>
        Subject currentUser = SecurityUtils.getSubject();
        <span class="hljs-comment">//5:绑定主体登录的身份/凭证,既账户及密码</span>
        UsernamePasswordToken token = <span class="hljs-keyword">new</span> UsernamePasswordToken(<span class="hljs-string">"root"</span>, <span class="hljs-string">"yubuntu0109"</span>);
        <span class="hljs-comment">//6:主体登录</span>
        <span class="hljs-keyword">try</span> &#123;
            currentUser.login(token);
            System.out.println(<span class="hljs-string">"用户身份是否验证成功 :"</span> + currentUser.isAuthenticated());
        &#125; <span class="hljs-keyword">catch</span> (UnknownAccountException e) &#123;
            System.err.println(<span class="hljs-string">"用户账户错误 !"</span>);
        &#125; <span class="hljs-keyword">catch</span> (IncorrectCredentialsException e) &#123;
            System.err.println(<span class="hljs-string">"用户密码错误 !"</span>);
        &#125; <span class="hljs-keyword">catch</span> (AuthenticationException e) &#123;
            e.printStackTrace();
        &#125;
        <span class="hljs-comment">//8:注销登录</span>
        currentUser.logout();
        System.out.println(<span class="hljs-string">"身份身份是否注销成功 :"</span> + !currentUser.isAuthenticated());

    &#125;
&#125;</code></pre></div>
</li>
<li><p><em>程序运行结果如下所示 :</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-comment">// ······</span>
用户身份是否验证成功 :<span class="hljs-keyword">true</span>
<span class="hljs-comment">// ······</span>
身份身份是否注销成功 :<span class="hljs-keyword">true</span></code></pre></div></li>
</ol>

            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/Java/">Java</a>
                    
                      <a class="hover-with-bg" href="/tags/Shiro/">Shiro</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/2019/08/02/Shiro%E4%B9%8B%E7%94%A8%E6%88%B7%E6%8E%88%E6%9D%83/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Shiro之用户授权</span>
                        <span class="visible-mobile">Previous</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/2019/08/01/%E8%AF%A6%E8%A7%A3Shiro%E7%99%BB%E5%BD%95%E7%99%BB%E5%87%BA%E7%9A%84%E6%93%8D%E4%BD%9C%E6%B5%81%E7%A8%8B/">
                        <span class="hidden-mobile">详解Shiro登录登出的操作流程</span>
                        <span class="visible-mobile">Next</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;TOC</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">Search</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">keyword</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


    

    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "Shiro之自定义realm及其加密&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>







  
  
    <script>
      !function (e, t, a) {
        function r() {
          for (var e = 0; e < s.length; e++) s[e].alpha <= 0 ? (t.body.removeChild(s[e].el), s.splice(e, 1)) : (s[e].y--, s[e].scale += .004, s[e].alpha -= .013, s[e].el.style.cssText = "left:" + s[e].x + "px;top:" + s[e].y + "px;opacity:" + s[e].alpha + ";transform:scale(" + s[e].scale + "," + s[e].scale + ") rotate(45deg);background:" + s[e].color + ";z-index:99999");
          requestAnimationFrame(r)
        }

        function n() {
          var t = "function" == typeof e.onclick && e.onclick;
          e.onclick = function (e) {
            t && t(), o(e)
          }
        }

        function o(e) {
          var a = t.createElement("div");
          a.className = "heart", s.push({
            el: a,
            x: e.clientX - 5,
            y: e.clientY - 5,
            scale: 1,
            alpha: 1,
            color: c()
          }), t.body.appendChild(a)
        }

        function i(e) {
          var a = t.createElement("style");
          a.type = "text/css";
          try {
            a.appendChild(t.createTextNode(e))
          } catch (t) {
            a.styleSheet.cssText = e
          }
          t.getElementsByTagName("head")[0].appendChild(a)
        }

        function c() {
          return "rgb(" + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + ")"
        }

        var s = [];
        e.requestAnimationFrame = e.requestAnimationFrame || e.webkitRequestAnimationFrame || e.mozRequestAnimationFrame || e.oRequestAnimationFrame || e.msRequestAnimationFrame || function (e) {
          setTimeout(e, 1e3 / 60)
        }, i(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"), n(), r()
      }(window, document);
    </script>
  














</body>
</html>
